//
//  HMStatusPictureView.swift
//  MicroBlog
//
//  Created by Apple on 16/9/25.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SDWebImage
//重用标记
private let HMStatusPictureViewCellIdentifier = "cell"
//每张图片之间的间距
let itemMargin: CGFloat = 5
//每张图片的宽度
let itemWidth = (ScreenWidth - 2 * HMHomeTableViewCellMargin - 2 * itemMargin) / 3
//自定义微博首页配图
class HMStatusPictureView: UICollectionView {
    //配图数据源
    var picUrls: [HMStatusPictureInfo]? {
        didSet {
            let size = calcSize(count: picUrls?.count ?? 0)
            //设置约束大小
            self.snp_updateConstraints { (make) in
                make.size.equalTo(size)
            }
            //加载设置数据
            self.reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        //水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //添加控件,设置约束
    private func setupUI() {
        //注册
        register(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: HMStatusPictureViewCellIdentifier)
        //设置代理
        self.dataSource = self
        self.delegate = self
    }
    
    //根据图片张数计算配图大小
    private func calcSize(count: Int) -> CGSize {
        //判断图片个数是否为1,如果为1,则从缓存中获取图片
        if count == 1 {
            let imageUrl = picUrls!.first!.thumbnail_pic!
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageUrl)
            if image != nil {
                var size = image!.size
                //图片过窄,高度过高,判断图片宽度小于指定大小,等比计算大小
                if size.width < 80{
                    let scaleWidth: CGFloat = 80
                    let height = scaleWidth / size.width * size.height
                    
                    let scaleHeight = height > 150 ? 150: height
                    
                    size.width = scaleWidth
                    size.height = scaleHeight
                }
                //不作处理,直接指定大小
//                size = CGSize(width: itemWidth, height: itemWidth)
                //调整条目大小
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = size
                //缓存图片存在
                return size
            }
        }
        //不是单张图片,还需要把条目大小修改回来
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //计算列数
        let cols = count > 3 ? 3 : count
        //计算行数
        let row = (count - 1) / 3 + 1
        //计算当前配图宽度
        let currentWidth = itemWidth * CGFloat(cols) + itemMargin * CGFloat(cols  - 1)
        //高度
        let currentHeight = itemWidth * CGFloat(row) + itemMargin * CGFloat(row - 1)
        return CGSize(width: currentWidth, height: currentHeight)
    }
}

//数据源方法
extension HMStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate,SDPhotoBrowserDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMStatusPictureViewCellIdentifier, for: indexPath) as! HMStatusPictureViewCell
        cell.statusPictureInfo = picUrls![indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    
    //返回小图
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! HMStatusPictureViewCell
        return cell.imageView.image
    }
    
    //返回高质量图片
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        return URL(string: urlStr)
    }
}

//自定义配图cell
class HMStatusPictureViewCell: UICollectionViewCell {
    //传入模型数据
    var statusPictureInfo: HMStatusPictureInfo? {
        didSet {
            if let url = statusPictureInfo?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
               
                if url.hasSuffix(".gif") {
                    gifImgView.isHidden = false
                } else {
                    gifImgView.isHidden = true
                }
            }
        }
    }
    //懒加载控件
    lazy var imageView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        view.contentMode = .scaleAspectFill
        //超出范围显示
        view.clipsToBounds = true
        return view
    }()
    //gif图
    private lazy var gifImgView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImgView)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        
        gifImgView.snp_makeConstraints { (make) in
            make.bottom.trailing.equalTo(imageView)
        }
    }
}
